import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:jetour_line/base_widget/base_scaffold.dart';
import 'package:jetour_line/base_widget/video_controller.dart';
import 'package:jetour_line/utils/extension_int.dart';
import 'package:video_player/video_player.dart';
import 'base_image.dart';

class VidewWidget extends StatefulWidget {
  final String path;
  final bool isPlay;
  const VidewWidget({super.key, required this.path,this.isPlay = false});

  @override
  State<VidewWidget> createState() => _VidewWidgetState();
}

class _VidewWidgetState extends State<VidewWidget> {
  //定义一个VideoPlayerController
  VideoPlayerController? _controller;
  bool isPlaying = false;
  bool isPause = false;
  bool isMute = false;//静音
  int curPosition = 0;
  int totalPosition = 0;
  int curTime = 0;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _controller = VideoPlayerController.network(widget.path)
      ..initialize().then((_) {
        // 确保在初始化视频后显示第一帧，直至在按下播放按钮。
        setState(() {});
      });


    _controller!.addListener(() {
      //播放进度
      int  cur = _controller!.value.position.inSeconds;
      int  total = _controller!.value.duration.inSeconds;
      if(curPosition == 0 && cur==total){//奇葩问题
        return;
      }
      curPosition = cur;
      totalPosition = total;
      if (cur == total) {
        curTime = 0;
        curPosition = 0;
        isPause = false;
        isPlaying = false;
        setState(() {
        });
      }else{
        setState(() {
        });
      }
    });
    if(widget.isPlay){
      if (!isPlaying){
        if (isPause) {
          isPause = false;
          _controller!.play();
        } else {
          _controller!
            ..seekTo( Duration(seconds: curTime))
            ..play();
        }
        isPlaying = true;
        setState(() {});
      }
    }
    //
  }


  String durationIndicatorBuilder(Duration duration) {
    const String separator = ':';
    final String minute = duration.inMinutes.toString().padLeft(2, '0');
    final String second =
    ((duration - Duration(minutes: duration.inMinutes)).inSeconds)
        .toString()
        .padLeft(2, '0');
    return '$minute$separator$second';
  }

  @override
  Widget build(BuildContext context) {
    String  totalPositionTxt = durationIndicatorBuilder(Duration(seconds: totalPosition));
    String  curPositionTxt = durationIndicatorBuilder(Duration(seconds: curPosition));
    return Column(
      children: [
        SizedBox(
          height: 96.px,
        ),
        Expanded(
          child: Center(
            child: Stack(
              alignment: Alignment.center,
              children: [
                _controller!.value.isInitialized
                    ? AspectRatio(
                        aspectRatio: _controller!.value.aspectRatio,
                        child: GestureDetector(
                            onTap: () {
                              if (isPlaying && !isPause) {
                                isPause = true;
                                isPlaying = false;
                                _controller!.pause();
                                setState(() {});
                              }
                            },
                            child: VideoPlayer(_controller!)),
                      )
                    //如果视频没有加载好或者因网络原因加载不出来则返回Container 组件
                    //一般用于放置过渡画面
                    : const SizedBox(),
                  GestureDetector(
                    onTap: () {
                      if (!isPlaying){
                        if (isPause) {
                          isPause = false;
                          _controller!.play();
                        } else {
                          _controller!
                            ..seekTo( Duration(seconds: curTime))
                            ..play();
                        }
                        isPlaying = true;
                        setState(() {});
                      }
                    },
                    child: isPlaying?const SizedBox(): BaseImage(
                      image: 'icon_gcvideo',
                      width: 100.px,
                      height: 100.px,
                    ),
                  ),
              ],
            ),
          ),
        ),
        Row(
          children: [
            SizedBox(
              width: 24.px,
              height: 96.px,
            ),
            GestureDetector(
              onTap: (){

                isMute = !isMute;
                if(isMute){
                  _controller!.setVolume(0.0); //音量
                }else{
                  _controller!.setVolume(1); //音量
                }
                setState(() {

                });
              },
              child: Container(
                  width: 96.px,
                  height: 96.px,
                  alignment: Alignment.center,
                  child: BaseImage(
                    image: isMute?'icon_gcvoice_no':'icon_gcvoice',
                    width: 52.px,
                    height: 52.px,
                  )),
            ),
            if(totalPosition>0)
            Expanded(child: Container(
              height: 20,
              child: VideoController(
                  totalTime:totalPosition,
                  changeTime:curPosition,
                  backgroundColor: Colors.white54,
                  progressColor: Colors.white,
                  thumbColor: Colors.white,
                  onVideoChangeEnd: (int value){
                    curTime = value;
                    _controller!.seekTo( Duration(seconds: value));
                  },
                  onVideoPlayClick: (isPlay) {
                    print("当前播放按钮状态$isPlay");
                  },
                  onVideoFullScreenClick: (isFullScreen) {
                    print("当前全屏按钮状态$isFullScreen");
                  },
                  onVideoChanged: (position) {
                    //返回毫秒
                    print("当前拖拽的进度$position");
                  }
              )
            )),
            Text(curPositionTxt,style: TextStyle(fontSize: 24.px,color: Colors.white),),
            Padding(padding: EdgeInsets.only(left: 10.px,right: 10.px,),child: Opacity(opacity: 0.6, child: Container(width: 1,height: 16.px,color: Colors.white,)),),
            Text(totalPositionTxt,style: TextStyle(fontSize: 24.px,color: Colors.white),),
            SizedBox(
              width: 24.px,
              height: 96.px,
            ),
          ],
        )
      ],
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _controller!.dispose();
  }
}
